
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-01-30
 * Time: 11:03
 */
public class BinarySearchTree {
    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        TreeNode node=new TreeNode(key);
        if(root==null){
            root=node;
            return true;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.key<key){
                parent=cur;
                cur=cur.right;
            }else if(cur.key>key){
                parent=cur;
                cur=cur.left;
            }else{
                return false;
            }
        }
        if(parent.key<key){
            parent.right=node;
        }else{
            parent.left=node;
        }

        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        if(root==null){
            return null;
        }
        TreeNode cur=root;
        while(cur!=null){
            if(cur.key<key){
                cur=cur.right;
            }else if(cur.key>key){
                cur=cur.left;
            }else{
                return cur;
            }
        }
        return null;
    }
    //删除key的值
    public boolean remove(int key) {
        if(root==null){
            return false;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.key<key){
                parent=cur;
                cur=cur.right;
            }else if(cur.key>key){
                parent=cur;
                cur=cur.left;
            }else{
                removeNode(parent,cur);
                return true;
            }
        }

        return false;
    }
    private void removeNode(TreeNode parent,TreeNode cur){
        if(cur.left==null){
            if(cur==root){
                root=root.right;
            }else if(cur==parent.left){
                parent.left=cur.right;
            }else{
                parent.right=cur.right;
            }

            }else if(cur.right==null){
                if(cur==root){
                    root=root.left;
                }else if(cur==parent.left){
                    parent.left=cur.left;
                }else{
                    parent.right=cur.left;
                }
          }else{
            TreeNode t=cur.right;
            TreeNode tp=cur;
            while(t.left!=null){
                tp=t;
                t=t.left;
            }
            cur.key=t.key;
            if(t==tp.left) {
                tp.left=t.right;
            }else{
                tp.right=t.right;
            }
        }

    }


}

